package com.cjxt.ams.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cjxt.ams.dao.MenuDao;
import com.cjxt.ams.dao.RoleDao;
import com.cjxt.ams.dao.RoleMenuDao;
import com.cjxt.ams.dao.UserDao;
import com.cjxt.ams.domain.*;
import com.cjxt.ams.service.*;
import com.cjxt.ams.utils.PageUtils;
import com.cjxt.ams.utils.R;
import com.cjxt.ams.utils.Result;
import io.swagger.models.auth.In;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @description: 角色
 * @author JK_a
 * @date 2021/11/23 14:18
 * @param
 */

@Service("roleService")
public class RoleServiceImpl extends ServiceImpl<RoleDao, Role> implements RoleService {

    @Autowired
    private RoleMenuService roleMenuService;

    @Autowired
    private RoleDeptService roleDeptService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private RoleMenuDao roleMenuDao;

    @Autowired
    private RoleDao roleDao;

    @Resource
    private UserDao userDao;

    @Resource
    private MenuDao menuDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        return null;
    }

    @Override
    public List<Role> findAll() {
        QueryWrapper<RoleMenu> qw = new QueryWrapper<>();
        //查询角色菜单表
        List<RoleMenu> roleMenus = roleMenuDao.selectList(qw);

        return roleService.findAll();
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public R insertRole(Role role) {

        QueryWrapper<Role> qw = new QueryWrapper();
        qw.eq("role_name", role.getRoleName());
        Integer integer = roleDao.selectCount(qw);
        if(integer > 0){
            return R.error("角色名重复！");
        }
        else {
            roleService.save(role);
            //保存角色与菜单的关系
            roleMenuService.saveOrUpdate(role.getRoleId(),role.getMenuIdList());
            return R.ok("新增角色成功！");
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public R update(Role role) {

        QueryWrapper<Role> qw = new QueryWrapper();
        qw.eq("role_name", role.getRoleName());
        Integer integer = roleDao.selectCount(qw);
        if (integer > 1){
            return R.error("已存在该角色名，修改失败！");
        }else {
            //修改时间
            role.setUpdateTime(new Date());
            roleDao.updateById(role);
            roleMenuService.saveOrUpdate(role.getRoleId(),role.getMenuIdList());
            return R.ok("角色修改成功！");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Integer[] roleIds) {

        /**
         * 删除角色
         */
        this.removeByIds(Arrays.asList(roleIds));

        /**
         * 删除角色与菜单关联
         */
        roleMenuService.deleteBatch(roleIds);

        /**
         * 删除角色与部门关联
         */
        roleDeptService.deleteBatch(roleIds);

        /**
         * 删除角色与用户关联
         */
        userRoleService.deleteBatch(roleIds);
    }

    @Override
    public void del(Integer userId) {
        QueryWrapper<UserRole> qw = new QueryWrapper<>();
        qw.eq("user_id", userId);

        userRoleService.remove(qw);

    }

    @Override
    public IPage<Role> selectRole(Role role) {

        IPage<Role> roleIPage = new Page<>(role.getPage(),role.getLimit());

        QueryWrapper qw = new QueryWrapper<>();

        if (StrUtil.isNotEmpty(role.getRoleName())){
            qw.like("role_name",role.getRoleName());
        }

        qw.orderBy(true,false,"id");
        roleIPage = roleDao.selectPage(roleIPage, qw);


        List<Role> list = roleIPage.getRecords();

        for (int i = 0; i < list.size(); i++) {
            Role role1 = list.get(i);
            List<Menu> menuList = menuDao.getMenusByRoleId(role1.getRoleId());

            String menuNames = "";
            String ids = "";

            for (int j = 0; j < menuList.size(); j++) {
                Menu menu = menuList.get(j);
                String str = menuDao.selectById(menu.getId()).getMenuName();
                String id = (menu.getId()).toString();
                if (j > 0){
                    if (j == menuList.size()){
                        menuNames += str;
                        ids += id;
                    }
                    menuNames += ","+str;
                    ids += ","+id;
                }
                else {
                    menuNames = str;
                    ids = id;
                }
            }

            role1.setMenuName(menuNames);
            role1.setId(ids);
        }

        return roleIPage;
    }

}
